var app = getApp();
const db = wx.cloud.database({
  env:'test-7gxzn7uuc171e9e9'
})
const order = db.collection("order")
const $ = db.command.aggregate
const _ = db.command

Page({
	data: {
		orderid:0,
		order_id:"",
		ifpay:false,
		goods: {
			1: {
				id: 1,
				name: '娃娃菜',
				pic: 'https://tse1-mm.cn.bing.net/th/id/OIP.MqErmkBRdBq0vSMA9c9QaQHaE7?w=270&h=180&c=7&o=5&pid=1.7',
				sold: 1014,
				price: 2
			},
			2: {
				id: 2,
				name: '金针菇',
				pic: 'https://tse1-mm.cn.bing.net/th/id/OIP.haDx270JFKFl6IO5uA-a7QHaE8?w=280&h=187&c=7&o=5&pid=1.7',
				sold: 1029,
				price: 3
			},
			3: {
				id: 3,
				name: '方便面',
				pic: 'https://tse1-mm.cn.bing.net/th/id/OIP._okUNpc8e9YXNqS4XoOwVQHaE6?w=260&h=180&c=7&o=5&pid=1.7',
				sold: 1030,
				price: 2
			},
			4: {
				id: 4,
				name: '粉丝',
				pic: 'https://tse2-mm.cn.bing.net/th/id/OIP.IRC6VnfRxdC-u0Uk8RBOjgHaE8?w=248&h=180&c=7&o=5&pid=1.7',
				sold: 1059,
				price: 1
			},
			5: {
				id: 5,
				name: '生菜',
				pic: 'https://tse1-mm.cn.bing.net/th/id/OIP.nPq5bx3iOcQdUC1e2BKLNAHaE9?w=296&h=198&c=7&o=5&pid=1.7',
				sold: 1029,
				price: 2
			},
			6: {
				id: 6,
				name: '白菜',
				pic: 'https://tse4-mm.cn.bing.net/th/id/OIP.eFLCvsK1Jhhe2fiNdyie2wHaHa?w=166&h=180&c=7&o=5&pid=1.7',
				sold: 1064,
				price: 2
			},
			7: {
				id: 7,
				name: '杏鲍菇',
				pic: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1865962543,3224801962&fm=26&gp=0.jpg',
				sold: 814,
				price: 3
			},
			8: {
				id: 8,
				name: '香菇',
				pic: 'https://tse4-mm.cn.bing.net/th/id/OIP.uskJrWu9bA7C4ziV_SFeqwHaE8?w=284&h=189&c=7&o=5&pid=1.7',
				sold: 124,
				price: 3
			},
			9: {
				id: 9,
				name: '猴头菇',
				pic: 'https://tse3-mm.cn.bing.net/th/id/OIP.M7y7V1DsS3Buy4CsJWUM3gHaGc?w=214&h=186&c=7&o=5&pid=1.7',
				sold: 102,
				price: 5
			}
		},
		goodsList: [
			{
				id: 'hot',
				classifyName: '热销',
				goods: [1, 2, 3, 4, 5]
			},
			{
				id: 'new',
				classifyName: '新品',
				goods: [1, 3]
			},
			{
				id: 'vegetable',
				classifyName: '蔬菜',
				goods: [1, 6, 5]
			},
			{
				id: 'mushroom',
				classifyName: '蘑菇',
				goods: [2, 7, 8, 9]
			},
			{
				id: 'food',
				classifyName: '主食',
				goods: [3, 4]
			}
		],
		cart: {//购物车，数量，总价，清单
			count: 0,
			total: 0,
			list: {}
		},
		showCartDetail: false,
		orderCount:{
      total:0,
      count:0
		}
	},
	onLoad: function (options) {
			console.log(options)
		var shopId = options.id;
		for (var i = 0; i < app.globalData.shops.length; ++i) {
			if (app.globalData.shops[i].id == shopId) {
				this.setData({
					shop: app.globalData.shops[i],
					address:options.address
				});
				break;
			}
			
		}

		if (this.data.order_id == "" || this.data.ifpay == "true") {//判断上一订单是否完成来添加新的订单
			order
			.aggregate()
			.group({
				_id: null,
				maxid: $.max('$orderid')
			}).end()
			.then(res => {
				this.setData({
					orderid:res.list[0].maxid
				})
	
				order.add({
					data: {
						orderid:res.list[0].maxid+1,
						goods: [
							{'goodsid':1,'amount':0,name:"娃娃菜"},
							{'goodsid':2,'amount':0,name:"金针菇"},
							{'goodsid':3,'amount':0,name:"方便面"},
							{'goodsid':4,'amount':0,name:"粉丝"},
							{'goodsid':5,'amount':0,name:"生菜"},
							{'goodsid':6,'amount':0,name:"白菜"},
							{'goodsid':7,'amount':0,name:"杏鲍菇"},
							{'goodsid':8,'amount':0,name:"香菇"},
							{'goodsid':9,'amount':0,name:"猴头菇"}
						],
						ifpay:false,
						total:0,
						createTime: db.serverDate()
					},
					success:res=>{
						this.setData({
							order_id:res._id,
							ifpay:res.ifpay
						})
						console.log(this.data.order_id)
					}
				})
			}).then(res=>{
				console.log("订单添加完成")
			})
		}

	},//商家
	onShow: function () {//左边的分类栏
		this.setData({
			classifySeleted: this.data.goodsList[0].id
		});
	},
	tapAddCart: function (e) {//
		this.addCart(e.target.dataset.id);
	},
	tapReduceCart: function (e) {
		this.reduceCart(e.target.dataset.id);
	},
	addCart: function (id) {//购物车添加
		var num = this.data.cart.list[id] || 0;
		this.data.cart.list[id] = num + 1;
		this.countCart();

//订单添加菜品,需要先添加订单
		console.log(this.data.order_id)
		order.where({
			'_id':this.data.order_id,
			'goods.goodsid':this.data.goods[id].id
		}).update({
			data:{
				'goods.$.amount':_.inc(1),
			},

		})

	},
	reduceCart: function (id) {//购物车减少
		var num = this.data.cart.list[id] || 0;
		if (num <= 1) {
			delete this.data.cart.list[id];
		} else {
			this.data.cart.list[id] = num - 1;
		}

		this.countCart();

		order.where({
			'_id':this.data.order_id,
			'goods.goodsid':this.data.goods[id].id
		}).update({
			data:{
				'goods.$.amount':_.inc(-1),
			},
		})

	},
	countCart: function () {
		var count = 0,
			total = 0;
		for (var id in this.data.cart.list) {
			var goods = this.data.goods[id];
			count += this.data.cart.list[id];
			total += goods.price * this.data.cart.list[id];
		}
		this.data.cart.count = count;
		this.data.cart.total = total;
		this.setData({
			cart: this.data.cart,
			total:this.data.cart.total
		});
		// let orderCount = {
    //   total,
    //   count
		// }
		// this.setData({
    //   orderCount:orderCount
    // });
	},
	follow: function () {//收藏
		this.setData({
			followed: !this.data.followed
		});
	},
	onGoodsScroll: function (e) {//商品数量大于10打开滚动条
		if (e.detail.scrollTop > 10 && !this.data.scrollDown) {
			this.setData({
				scrollDown: true
			});
		} else if (e.detail.scrollTop < 10 && this.data.scrollDown) {
			this.setData({
				scrollDown: false
			});
		}

		var scale = e.detail.scrollWidth / 570,
			scrollTop = e.detail.scrollTop / scale,
			h = 0,
			classifySeleted,
			len = this.data.goodsList.length;
		this.data.goodsList.forEach(function (classify, i) {
			var _h = 70 + classify.goods.length * (46 * 3 + 20 * 2);
			if (scrollTop >= h - 100 / scale) {
				classifySeleted = classify.id;
			}
			h += _h;
		});
		this.setData({
			classifySeleted: classifySeleted
		});
	},
	tapClassify: function (e) {//分类
		var id = e.target.dataset.id;
		this.setData({
			classifyViewed: id
		});
		var self = this;
		setTimeout(function () {
			self.setData({
				classifySeleted: id
			});
		}, 100);
	},
	showCartDetail: function () {
		this.setData({
			showCartDetail: !this.data.showCartDetail
		});
	},
	hideCartDetail: function () {
		this.setData({
			showCartDetail: false
		});
	},
	submit: function (e) {

		let that = this;
		let str = '您选中' + that.data.cart.count + '件商品，共' + that.data.cart.total + '元，是否要支付？'

		order.doc(this.data.order_id).update({
			data:{
				total:this.data.cart.total,
			},
		})

   wx.showModal({
				 title: '亲爱的顾客',
				 content: str,
        //  content: '订单发送成功！',
         showCancel: true,//是否显示取消按钮
         cancelText:"等等",//默认是“取消”
        //  cancelColor:'skyblue',//取消文字的颜色 ，真机显示不出  
         confirmText:"去支付",//默认是“确定”
        //  confirmColor: 'skyblue',//确定文字的颜色
         success: function (res) {
            if (res.cancel) {
               //点击取消,默认隐藏弹框
            } else {
               //点击确定
              //  temp.splice(index, 1),
              //  that.setData({
              //     tempFilePaths: temp,
							//  })

							//  var total = this.data.cart;
							wx.navigateTo({    //保留当前页面，跳转到应用内的某个页面（最多打开5个页面，之后按钮就没有响应的）
								url:'/page/pay/pay?total='+that.data.cart.total+ '&count='+that.data.cart.count+'&address='+that.data.address
								+'&order_id='+that.data.order_id,
					 })
            }
         },
         fail: function (res) { },//接口调用失败的回调函数
         complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
      })
		
	},

});

